package com.example.yilanchatserver.business.freechat;


import com.alibaba.fastjson.JSONObject;
import com.example.yilanchatserver.business.freechat.service.dto.ErnieBotReqDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class ErnieBotWebClient {
    private WebClient webClient;

    @Value("${ernieBot.modelURL}")
    private String chatApi;

    @PostConstruct
    public void init() {
        initProd();
    }

    public void initProd() {
        log.info("initProd");
        this.webClient = WebClient.builder()
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .build();
    }

    public Flux<String> getChatResponse(ErnieBotReqDTO reqDTO, String accessToken) {
        JSONObject bodyParams = new JSONObject();
        bodyParams.put("messages", reqDTO.getMessages());
        bodyParams.put("temperature", reqDTO.getTemperature());
        bodyParams.put("top_p", reqDTO.getTopP());
        bodyParams.put("penalty_score", reqDTO.getPenaltyScore());
        bodyParams.put("stream", reqDTO.getStream());
        bodyParams.put("user_id", reqDTO.getUserId());

        return webClient.post()
                .uri(chatApi + "?access_token=" + accessToken)
                .bodyValue(bodyParams.toJSONString())
                .retrieve()
                .bodyToFlux(String.class)
                .onErrorResume(WebClientResponseException.class, ex -> {
                    HttpStatus status = ex.getStatusCode();
                    String res = ex.getResponseBodyAsString();
                    log.error("ErnieBot API error: {} {}", status, res);
                    return Mono.error(new RuntimeException(res));
                });

    }
}
